import { createClient } from "../client";
import { ClientFn } from "../types/core";

import { SessionAnnotation, toSessionAnnotationData } from "./types";

/**
 * Parameters to log multiple session annotations
 */
export interface LogSessionAnnotationsParams extends ClientFn {
  /**
   * The session annotations to log
   */
  sessionAnnotations: SessionAnnotation[];
  /**
   * If true, the request will be fulfilled synchronously and return the annotation IDs.
   * If false, the request will be processed asynchronously and return null.
   * @default false
   */
  sync?: boolean;
}

/**
 * Log multiple session annotations in a single request.
 *
 * Each annotation can be of type "LLM", "CODE", or "HUMAN" and can include a label, score, and metadata.
 * If an identifier is provided and an annotation with that identifier already exists, it will be updated.
 *
 * @param params - The parameters to log session annotations
 * @returns The IDs of the created or updated annotations
 *
 * @example
 * ```ts
 * const results = await logSessionAnnotations({
 *   sessionAnnotations: [
 *     {
 *       sessionId: "123abc",
 *       name: "quality_score",
 *       label: "good",
 *       score: 0.95,
 *       annotatorKind: "LLM",
 *       identifier: "custom_id_123",
 *       metadata: {
 *         model: "gpt-4"
 *       }
 *     },
 *     {
 *       sessionId: "456def",
 *       name: "sentiment",
 *       label: "positive",
 *       score: 0.8,
 *       annotatorKind: "CODE"
 *     }
 *   ]
 * });
 * ```
 */
export async function logSessionAnnotations({
  client: _client,
  sessionAnnotations,
  sync = false,
}: LogSessionAnnotationsParams): Promise<{ id: string }[]> {
  const client = _client ?? createClient();

  const { data, error } = await client.POST("/v1/session_annotations", {
    params: {
      query: { sync },
    },
    body: {
      data: sessionAnnotations.map(toSessionAnnotationData),
    },
  });

  if (error) {
    throw new Error(`Failed to log session annotations: ${error}`);
  }

  return data?.data || [];
}
